<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				slot="page-search"
				ref="form"
				:inline="true"
				:model="queryData"
				class="flex-warp-container"
				label-suffix=":"
				label-width="100px"
			>
				<el-form-item label="订单号" class="flex-row-container">
					<el-input
						v-input="{ name: 'num' }"
						clearable
						v-model="queryData.id"
						:placeholder="$t('common.please_enter')"
						style="width: 200px"
					/>
				</el-form-item>
				<el-form-item label="三方订单号" class="flex-row-container">
					<el-input
						v-input="{ name: 'symbols' }"
						clearable
						v-model="queryData.orderNo"
						:placeholder="$t('common.please_enter')"
						style="width: 220px"
					/>
				</el-form-item>
				<el-form-item label="会员账号" class="flex-row-container">
					<el-input
						v-input="{ name: 'symbols' }"
						clearable
						v-model="queryData.userName"
						:placeholder="$t('common.please_enter')"
						style="width: 180px"
					/>
				</el-form-item>
				<el-form-item
					:label="$t('dxn.card_ables_list.game_name')"
					class="flex-row-container"
				>
					<el-select
						v-model="queryData.gameTypeList"
						clearable
						:placeholder="$t('common.select_all')"
						multiple
						style="width:220px"
					>
						<el-option
							v-for="item in gameType"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item
					:label="`会员所属俱乐部ID`"
					prop="userClubId"
					label-width="135px"
					class="flex-row-container"
				>
					<el-input
						v-model.trim="queryData.userClubId"
						v-input="{ name: 'num' }"
						clearable
						style="width: 150px"
						:placeholder="`${$t('common.please_enter')}`"
					></el-input>
				</el-form-item>
				<el-form-item label="牌桌ID" class="flex-row-container">
					<el-input
						v-input="{ name: 'symbols' }"
						clearable
						v-model="queryData.tableCode"
						:placeholder="$t('common.please_enter')"
						style="width: 300px"
					/>
				</el-form-item>
				<el-form-item label="下单时间" class="flex-row-container">
					<el-date-picker
						:clearable="false"
						v-model="orderTime"
						size="medium"
						:picker-options="pickerShortcut2"
						format="yyyy-MM-dd HH:mm:ss"
						type="datetimerange"
						range-separator="-"
						:start-placeholder="$t('common.start_time')"
						:end-placeholder="$t('common.end_time')"
						align="right"
						value-format="timestamp"
						style="width: 360"
						:default-time="defaultTime"
					></el-date-picker>
				</el-form-item>
				<el-form-item label="结算时间" class="flex-row-container">
					<el-date-picker
						:clearable="false"
						v-model="netTime"
						size="medium"
						:picker-options="pickerShortcut2"
						format="yyyy-MM-dd HH:mm:ss"
						type="datetimerange"
						range-separator="-"
						:start-placeholder="$t('common.start_time')"
						:end-placeholder="$t('common.end_time')"
						align="right"
						value-format="timestamp"
						style="width: 360px"
						:default-time="defaultTime"
					></el-date-picker>
				</el-form-item>
				<el-form-item
					label="牌桌所属俱乐部ID"
					label-width="135px"
					class="flex-row-container"
				>
					<el-input
						v-input="{ name: 'num' }"
						clearable
						v-model="queryData.clubId"
						:placeholder="$t('common.please_enter')"
						style="width: 150px"
					/>
				</el-form-item>
				<el-form-item label="订单类型" class="flex-row-container">
					<el-select
						v-model="queryData.parentOrderTypeList"
						clearable
						:placeholder="$t('common.select_all')"
						multiple
						style="width:280px"
					>
						<el-option
							v-for="item in parentOrderTypeSelect"
							:key="item.description"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="订单子类" class="flex-row-container">
					<el-select
						v-model="queryData.orderTypeList"
						clearable
						:placeholder="$t('common.select_all')"
						multiple
						style="width:280px"
					>
						<el-option
							v-for="item in sonOrderTypeSelect"
							:key="item.description"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item class="flex-row-container">
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						:loading="loading"
						size="medium"
						@click="search"
					>
						{{ $t('common.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-left"
						:disabled="loading"
						size="medium"
						@click="reset"
					>
						{{ $t('common.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('90360063')"
						type="warning"
						icon="el-icon-download"
						size="medium"
						:disabled="exportloading"
						:loading="exportloading"
						@click="handleExport"
					>
						{{ $t('dxn.card_ables_list.export_excel') }}
					</el-button>
					<el-button
						v-if="hasPermission('90870094')"
						type="success"
						icon="el-icon-sort"
						size="medium"
						@click="showColumnSet"
					>
						{{ $t('common.row_set') }}
					</el-button>
				</el-form-item>
			</el-form>
		</template>
		<template slot="content">
			<el-table
				ref="refTable"
				@current-change="handleSelectRowHighlight"
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				border
				size="mini"
				:data="dataList"
				style="width: 100%"
				:max-height="tableHeight"
				highlight-current-row
				:header-cell-style="getRowClass"
				@sort-change="handleTableSort"
				show-summary
				:summary-method="
					(val) => handleRow(val, subSummary, totalSummary)
				"
			>
				<el-table-column
					type="index"
					label="序号"
					width="120"
					align="center"
				/>
				<el-table-column label="订单号" min-width="190" align="center">
					<template slot-scope="scope">
						{{ scope.row.id }}
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.orderNo]"
					label="三方订单号"
					min-width="190"
					align="center"
				>
					<template slot-scope="scope">
						{{ scope.row.orderNo || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.userName]"
					label="会员账号"
					min-width="130"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.userName || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.userClubId]"
					label="会员所属俱乐部ID"
					min-width="125"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<div
							v-if="scope.row.userClubId"
							class="text-link"
							@click="
								$router.push({
									path: '/dxn/clubManager/clubList',
									query: {
										clubId: scope.row.userClubId
									}
								})
							"
						>
							{{ scope.row.userClubId }}
						</div>
						<div v-else>-</div>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.parentOrderTypeDesc]"
					align="center"
					label="订单类型"
					min-width="150"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>
							{{ scope.row.parentOrderTypeDesc || '-' }}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.orderTypeDesc]"
					align="center"
					label="订单子类"
					min-width="150"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>{{ scope.row.orderTypeDesc || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.payType]"
					align="center"
					label="收支类型"
					min-width="120"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>
							{{ getTypeName(scope.row.payType, payTypeArr) }}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.orderTime]"
					label="下单时间"
					min-width="160"
					align="center"
					show-overflow-tooltip
					prop="orderTime"
					sortable="custom"
				>
					<template slot-scope="scope">
						<span>{{ parseTime(scope.row.orderTime) || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.orderStatus]"
					label="订单状态"
					min-width="120"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.orderStatus === 1 ? '已结算' : '未结算' }}
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.netTime]"
					label="结算时间"
					min-width="160"
					align="center"
					show-overflow-tooltip
					prop="netTime"
					sortable="custom"
				>
					<template slot-scope="scope">
						{{ parseTime(scope.row.netTime) || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.originOrderId]"
					label="来源订单号"
					min-width="200"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.originOrderId || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.remark]"
					label="备注"
					min-width="180"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.remark || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.subOrderTypeCode]"
					label="细类编号"
					min-width="150"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.subOrderTypeCode || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.subOrderTypeDesc]"
					label="细类名称"
					min-width="150"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.subOrderTypeDesc || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.tableCode]"
					label="牌桌ID"
					min-width="210"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<div
							v-if="scope.row.tableCode"
							class="text-link"
							@click="
								$router.push({
									path:
										'/dxn/gameManager/cardTablesList/cardTablesBase',
									query: {
										tableId: scope.row.tableCode
									}
								})
							"
						>
							{{ scope.row.tableCode }}
						</div>
						<div v-else>
							-
						</div>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.tableName]"
					label="牌桌名称"
					min-width="160"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.tableName || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.gameType]"
					label="游戏名称"
					min-width="120"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ typeFilter(scope.row.gameType, 'gameType') }}
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.clubId]"
					label="牌桌所属俱乐部ID"
					min-width="125"
					align="center"
				>
					<template slot-scope="scope">
						<div
							v-if="scope.row.clubId"
							class="text-link"
							@click="
								$router.push({
									path: '/dxn/clubManager/clubList',
									query: {
										clubId: scope.row.clubId
									}
								})
							"
						>
							{{ scope.row.clubId }}
						</div>
						<div v-else>-</div>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.orderAmount]"
					label="订单金额"
					min-width="160"
					align="center"
					show-overflow-tooltip
					prop="orderAmount"
					sortable="custom"
				>
					<template slot-scope="scope">
						<span>
							{{
								handleNumber(
									scope.row.currency,
									scope.row.orderAmount
								)
							}}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.preferentialAmount]"
					label="优惠金额"
					min-width="160"
					align="center"
					show-overflow-tooltip
					prop="preferentialAmount"
					sortable="custom"
				>
					<template slot-scope="scope">
						<span>
							{{
								handleNumber(
									scope.row.currency,
									scope.row.preferentialAmount
								)
							}}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.payAmount]"
					label="实付/实得金额"
					min-width="160"
					align="center"
					show-overflow-tooltip
					prop="payAmount"
					sortable="custom"
				>
					<template slot-scope="scope">
						<span>
							{{
								handleNumber(
									scope.row.currency,
									scope.row.payAmount
								)
							}}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.serviceContribution]"
					label="订单纯利"
					min-width="160"
					align="center"
					show-overflow-tooltip
					prop="serviceContribution"
					sortable="custom"
				>
					<template slot-scope="scope">
						<span>
							{{
								handleNumber(
									scope.row.currency,
									scope.row.serviceContribution
								)
							}}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.orderIp]"
					label="下单ip"
					min-width="120"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span>{{ scope.row.orderIp || '-' }}</span>
					</template>
				</el-table-column>
				<el-table-column
					v-if="tableColumnData[tableColumns.obDeviceType]"
					label="下单终端"
					min-width="120"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{
							typeFilter(scope.row.obDeviceType, 'gameDeviceType')
						}}
					</template>
				</el-table-column>
				<el-table-column
					align="center"
					label="操作"
					width="120"
					fixed="right"
				>
					<template slot-scope="scope">
						<el-button
							type="primary"
							size="medium"
							@click="showDetail(scope.row.id, scope.$index)"
						>
							{{ $t('common.check_detail') }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>

			<el-pagination
				v-if="total"
				class="pageValue"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:current-page.sync="pageNum"
				:page-size="pageSize"
				:page-sizes="pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			/>
		</template>
		<Detail
			:visible.sync="detail.visible"
			:detailLoading="detail.loading"
			:detail="detail.info"
			:recordLength="recordLength"
			:currentRecordIndex="currentRecordIndex"
			@getPrevAndNextDetail="getPrevAndNextDetail"
		></Detail>
		<TableColumnSet
			v-if="colSettings.visible"
			:visible.sync="colSettings.visible"
			:dialogColumnData="dialogColumnData"
			:activityListField="activityListField"
			@submitColumnSet="submitColumnSet"
			@choiceColumnSet="choiceColumnSet"
		></TableColumnSet>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import { routerNames } from '@/utils/consts'
import Detail from '../components/Detail'
import dayjs from 'dayjs'
import MainContent from '@/components/MainContent/index.vue'
import summaryList from './components/summaryList'
import tableScroll from '@/utils/tableScroll'
import { tableColumns } from './components/tableColumn'
import TableColumnSet from '@/components/Dxn/TableColumnSet'
import dxnMixin from '@/mixins/dxnMixin'
const start = () =>
	dayjs()
		.startOf('day')
		.subtract(6, 'day')
const end = () => dayjs().endOf('day')

export default {
	name: routerNames.orderList,
	components: {
		TableColumnSet,
		Detail,
		MainContent
	},
	mixins: [list, summaryList, tableScroll, dxnMixin],
	data() {
		return {
			tableHeight: 480,
			otherDependenComponents: [],
			loading: false,
			exportloading: false,
			total: 0,
			dataList: [],
			subSummary: {},
			totalSummary: {},
			orderTime: [start(), end()],
			netTime: [start(), end()],
			queryData: {
				id: undefined,
				orderNo: undefined,
				userName: undefined,
				gameTypeList: [],
				clubId: undefined,
				userClubId: undefined,
				tableCode: undefined,
				parentOrderTypeList: [],
				orderTypeList: []
			},
			recordLength: 0,
			currentRecordIndex: 0,
			detail: {
				visible: false,
				loading: false,
				info: {}
			},
			payTypeArr: [
				{
					code: 1,
					description: '支出'
				},
				{
					code: 2,
					description: '收入'
				}
			],
			allOrderTypeMap: new Map(),
			parentOrderTypeSelect: [],
			sonOrderTypeSelect: [],
			tableColumns
		}
	},
	computed: {
		gameType() {
			return this.globalDics.gameType || []
		}
	},
	watch: {
		$route: function(to, from) {
			if (to.path.indexOf(routerNames.orderList) > -1) {
				this.getRouteQuery(true)
			}
		},
		'queryData.parentOrderTypeList': {
			handler(val) {
				this.queryData.orderTypeList = []
				if (Array.isArray(val)) {
					if (val.length) {
						this.sonOrderTypeSelect = []
						val.forEach((item) => {
							this.sonOrderTypeSelect = this.sonOrderTypeSelect.concat(
								this.allOrderTypeMap.get(Number(item)) || []
							)
						})
					} else {
						this.sonOrderTypeSelect = this.allOrderTypeMap.get(0)
					}
				}
			}
		}
	},
	created() {
		this.initIndexDB('orderList', this.activityListField)
		this.getRouteQuery()
		this.getOrderTypeSection()
	},
	methods: {
		// 请求
		getRouteQuery(isLoadData = false) {
			if (this.$route.query.tableId || this.$route.query.orderId) {
				this.resetQueryData()
				this.orderTime = []
				this.netTime = []
				this.queryData.tableCode = this.$route.query.tableId || ''
				this.queryData.id = this.$route.query.orderId || ''
				this.$router.replace({ query: {} })
				if (isLoadData) {
					this.loadData()
				}
			}
		},
		getOrderTypeSection() {
			this.allOrderTypeMap = new Map()
			this.parentOrderTypeSelect = []
			this.sonOrderTypeSelect = []
			this.$api
				.getOrderTypeSectionBend()
				.then((res) => {
					if (res?.code === 200 && Array.isArray(res?.data)) {
						const allSonItem = []
						res.data.forEach((item) => {
							this.parentOrderTypeSelect.push({
								code: item.type,
								description: item.desc
							})
							const sonItem = []
							if (Array.isArray(item?.subList)) {
								item.subList.forEach((row) => {
									const rowItem = {
										code: row.type,
										description: row.desc
									}
									sonItem.push(rowItem)
									allSonItem.push(rowItem)
								})
							}
							this.allOrderTypeMap.set(item.type, sonItem)
						})
						this.sonOrderTypeSelect = [...allSonItem]
						this.allOrderTypeMap.set(0, allSonItem)
					}
				})
				.catch(() => {})
		},
		getNewPlusTimeStamp(val) {
			if (val.toString().slice(-3) === '000') {
				return val + 999
			} else {
				return val
			}
		},
		getSearchParams() {
			const orderTime = this.orderTime || []
			const netTime = this.netTime || []
			const params = {
				...this.queryData,
				orderTimeFrom: orderTime[0]
					? dayjs(orderTime[0]).valueOf()
					: undefined,
				orderTimeTo: orderTime[1]
					? dayjs(orderTime[1]).valueOf()
					: undefined,
				netTimeFrom: netTime[0]
					? dayjs(netTime[0]).valueOf()
					: undefined,
				netTimeTo: netTime[1] ? dayjs(netTime[1]).valueOf() : undefined
			}
			// 判断搜索结束时间戳是否需要添加999毫秒
			if (params.orderTimeTo) {
				params.orderTimeTo = this.getNewPlusTimeStamp(
					params.orderTimeTo
				)
			}
			if (params.netTimeTo) {
				params.netTimeTo = this.getNewPlusTimeStamp(params.netTimeTo)
			}

			if (!params.gameTypeList?.length) {
				params.gameTypeList = undefined
			}
			if (!params.parentOrderTypeList?.length) {
				params.parentOrderTypeList = undefined
			}
			if (!params.orderTypeList?.length) {
				params.orderTypeList = undefined
			}
			return params
		},
		loadData() {
			this.loading = true
			const params = this.getParams(this.getSearchParams())
			this.dataList = []
			this.subSummary = {}
			this.totalSummary = {}
			this.recordLength = 0
			this.$api
				.getOrderListBend(params)
				.then((res) => {
					this.loading = false
					if (res?.code === 200) {
						this.dataList = res.data.record
						this.total = res.data.totalRecord
						this.recordLength = this.dataList.length
						this.subSummary = res.data?.summary[0] || {}
						this.totalSummary = res.data?.summary[1] || {}
					}
				})
				.catch(() => {
					this.loading = false
				})
		},
		search() {
			this.clearTableSort()
			this.pageNum = 1
			this.loadData()
		},
		reset() {
			this.resetQueryData()
			this.pageNum = 1
			this.orderTime = [start(), end()]
			this.netTime = [start(), end()]
			this.loadData()
		},
		// 列表导出
		handleExport() {
			const params = this.getParams(this.getSearchParams())
			this.deleteExportParams(params)
			this.exportloading = true
			this.exportExcelPublic({
				api: 'exportOrderListBend',
				params
			}).finally(() => {
				this.exportloading = false
			})
		},
		// 详情
		showDetail(id, index) {
			this.detail = {
				visible: true,
				loading: true,
				info: {}
			}
			this.currentRecordIndex = index
			this.getDetail(id)
		},
		getDetail(id) {
			this.detail.loading = true
			this.detail.info = {}
			const params = {
				id: id
			}
			this.$api
				.getOrderDetailBend(params)
				.then((res) => {
					this.detail.loading = false
					if (res?.code === 200) {
						this.detail.info = Object.assign({}, res.data)
						this.detail.info.payTypeName = this.getTypeName(
							this.detail.info.payType,
							this.payTypeArr
						)
					}
				})
				.catch(() => {
					this.detail.loading = false
				})
		},
		// 获取上一条,下一条
		getPrevAndNextDetail(type) {
			// type 1上一条  2下一条
			const index =
				type === 1
					? this.currentRecordIndex - 1
					: this.currentRecordIndex + 1
			if (this.dataList[index]) {
				this.currentRecordIndex = index
				this.getDetail(this.dataList[index].id)
			}
		}
	}
}
</script>
<style lang="scss" scoped>
::v-deep .el-dialog__header {
	color: #909399;
	font-weight: 700;
}
::v-deep .el-table__fixed-footer-wrapper .cell,
::v-deep .el-table__footer-wrapper .cell {
	height: 100%;
	padding: 0 !important;
	margin: 0 !important;
	> div {
		height: 100%;
	}
}
::v-deep .footer_count_row {
	min-height: 50px;
	height: 50%;
	display: flex;
	font-weight: 700;
	padding: 5px 0;
	align-items: center;
	flex-direction: column;
	justify-content: center;
}
::v-deep .footer_count_row_border {
	border-top: 1px solid #ebeef5;
}
</style>
